package pl.kosmowska.ewelina.client.app.activity;

import pl.kosmowska.ewelina.client.app.ClientFactory;
import pl.kosmowska.ewelina.client.app.activity.places.IncomeOutcomePlace;
import pl.kosmowska.ewelina.client.app.activity.places.SignInPlace;
import pl.kosmowska.ewelina.client.app.user.AuthEvent;
import pl.kosmowska.ewelina.client.app.user.AuthEvent.Auth;
import pl.kosmowska.ewelina.client.app.user.AuthEventHandler;
import pl.kosmowska.ewelina.client.views.SignInView;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class SignInActivity extends AbstractActivity implements SignInView.Presenter {

  private SignInView view;
  
  private ClientFactory clientFactory;

  
  public SignInActivity(SignInPlace place, ClientFactory clientFactory) {
    this.clientFactory = clientFactory;
  }


  @Override
  public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
    view = clientFactory.getSignInView();
    view.setPresenter(this);
    initAuthorisationForView();
    containerWidget.setWidget(view.asWidget());
  }

	private void initAuthorisationForView() {
		if (view.isAlreadyInit() == false) {
			clientFactory.getEventBus().addHandler(AuthEvent.TYPE, new AuthEventHandler() {
				public void onAuthEvent(AuthEvent event) {
					Auth e = event.getAuthEvent();
					if (e == Auth.LOGGEDIN) {
					    view.showLoading(false);
					    goTo(new IncomeOutcomePlace());
					} else if (e == Auth.LOGGEDOUT) {
						view.setLoggedOut(event.getUserData());
					}
				}
			});
		}
		view.setAlreadyInit(true);
	}

  public void goTo(Place place) {
    clientFactory.getPlaceController().goTo(place);
  }
  

}
